from app.crud.base_crud import BaseCRUD
from app.models import Api
from app.models.operation_log import OperationLog
from app.schemas.operation_log_schema import OperationLogCreate


class OperationLogCRUD(BaseCRUD[OperationLog, OperationLogCreate, None]):
    async def create(self, obj: OperationLogCreate) -> OperationLog:
        """
        创建新数据
        :param obj: 创建数据的schema
        :return: 创建的数据对象
        :raises HTTPException: 409 如果数据已存在
        """
        api = await self.context.set(Api).where(Api.path == obj.api_path, Api.is_enabled == True).scalar_one_or_none()
        if api is not None:
            obj.api_label = api.label or api.name
        db_obj = self.model.model_validate(obj)
        result = await self.context.add(entity=db_obj)
        return result
